<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useHistoryStore } from '@/stores/history.js'
import { storeToRefs } from 'pinia'

const router = useRouter()

const historyStore = useHistoryStore()
const { historyList } = storeToRefs(historyStore)
const { addHistory, clearHistory } = historyStore

const value = ref('')

const search = () => {
  if (value.value) {
    addHistory(value.value)
    router.push(`/list?keyword=${value.value}`)
  }
}

const clear = () => {
  clearHistory()
}

const setValue = (v) => {
  value.value = v
}
</script>

<template>
  <div class="search">
    <van-nav-bar
      title="商品搜索"
      left-arrow
      fixed
      @click-left="$router.back()"
    />
    <div class="search-input">
      <van-icon name="search" size="14px" />
      <input type="text" placeholder="请输入您搜索的商品" v-model="value" />
      <button @click="search">搜索</button>
    </div>

    <div class="history">
      <p class="header">
        <span>最近搜索</span>
        <van-icon name="delete-o" size="14px" @click="clear" />
      </p>
      <div class="list">
        <span
          v-for="(item, index) in historyList"
          :key="index"
          @click="setValue(item)"
          >{{ item }}</span
        >
      </div>
    </div>
  </div>
</template>

<style lang="less" scoped>
.search {
  padding-top: 46px;
}

.van-nav-bar {
  ::v-deep .van-nav-bar__title {
    font-weight: bold;
  }

  ::v-deep .van-icon-arrow-left {
    color: black;
  }
}

.search-input {
  width: 355px;
  height: 32px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  background-color: white;
  margin: 10px;
  color: grey;

  input {
    width: 254px;
    height: 32px;
    border: none;
    font-size: 14px;
    opacity: 1;
    padding-left: 5px;
  }

  button {
    height: 32px;
    width: 71px;
    font-size: 14px;
    border-radius: 0 5px 5px 0;
    background: #fa2209;
    color: #fff;
    border: none;
  }
}

.history {
  width: 355px;
  height: 146px;
  margin: 10px;
  margin-top: 30px;

  .header {
    display: flex;
    justify-content: space-between;
    color: #777;
    font-size: 14px;
    margin-bottom: 30px;
  }

  .list {
    display: flex;
    flex-flow: row wrap;
    justify-content: space-between;

    span {
      width: 106px;
      height: 30px;
      text-align: center;
      line-height: 30px;
      border-radius: 50px;
      background: #fff;
      font-size: 13px;
      border: 0.5px solid #efefef;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      margin-bottom: 10px;
    }
  }

  .list:after {
    display: block;
    content: '';
    width: 30%;
    height: 0px;
  }
}
</style>
